package com.app.gamev2.ui.game

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.activity.ComponentActivity
import com.app.gamev2.R
import com.app.gamev2.objects.Player
import com.app.gamev2.game.GameConfig
import com.app.gamev2.game.GameManager
import com.app.gamev2.ui.splash.SplashActivity
import com.app.gamev2.utils.VibrationUtils
import java.util.*

/**
 * 游戏界面入口，管理游戏生命周期和界面交互
 */
class GameActivity : ComponentActivity() {
    // 游戏视图
    private lateinit var gameView: GameView
    
    // 玩家对象
    private lateinit var player: Player
    
    // 游戏管理器
    private lateinit var gameManager: GameManager
    
    // UI元素
    private lateinit var bucketLevelText: TextView
    private lateinit var heightText: TextView
    private lateinit var jumpButton: Button
    private lateinit var leftButton: Button
    private lateinit var rightButton: Button
    private lateinit var bucketIcon: ImageView
    private lateinit var resultDialog: View
    private lateinit var gameOverText: TextView
    private lateinit var finalHeightText: TextView
    private lateinit var finalLevelText: TextView
    private lateinit var restartButton: Button
    private lateinit var backButton: Button
    
    // 游戏循环处理器
    private val gameHandler = Handler(Looper.getMainLooper())
    
    // 游戏循环相关变量
    private var lastFrameTime = 0L
    
    // 游戏循环Runnable
    private val gameLoopRunnable = object : Runnable {
        override fun run() {
            // 计算实际的deltaTime
            val currentTime = System.nanoTime()
            val deltaTimeNanos = currentTime - lastFrameTime
            val deltaTime = minOf(deltaTimeNanos / 1_000_000_000f, 0.1f) // 转换为秒并限制最大值
            lastFrameTime = currentTime
            
            // 更新游戏状态
            gameManager.update(deltaTime)
            
            // 更新UI
            updateUI()
            
            // 重新绘制游戏视图
            gameView.updateAndInvalidate()
            
            // 检查游戏状态
            when (gameManager.gameState) {
                GameConfig.GameState.WIN -> showResultDialog(true)
                GameConfig.GameState.LOSE -> showResultDialog(false)
                else -> gameHandler.post(this) // 使用post而不是postDelayed，让系统决定下一次运行时机
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_game)

        // 初始化UI元素
        bucketLevelText = findViewById(R.id.bucket_level_text)
        heightText = findViewById(R.id.height_text)
        jumpButton = findViewById(R.id.jump_button)
        leftButton = findViewById(R.id.left_button)
        rightButton = findViewById(R.id.right_button)
        bucketIcon = findViewById(R.id.bucket_icon)
        resultDialog = findViewById(R.id.result_dialog)
        gameOverText = findViewById(R.id.game_over_text)
        finalHeightText = findViewById(R.id.final_height_text)
        finalLevelText = findViewById(R.id.final_level_text)
        restartButton = findViewById(R.id.restart_button)
        backButton = findViewById(R.id.back_button)

        // 创建玩家对象
        val playerView = findViewById<ImageView>(R.id.player_view)
        player = Player(this, playerView)

        // 创建游戏管理器
        gameManager = GameManager(this, player)

        // 创建并初始化游戏视图
        val gameContainer = findViewById<ViewGroup>(R.id.game_container)
        gameView = GameView(this, null)
        gameView.layoutParams = ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )
        gameView.setGameManager(gameManager)
        gameView.setPlayer(player)
        gameContainer.addView(gameView)

        // 设置按钮点击事件
        jumpButton.setOnClickListener {
            // 触发跳跃，支持连跳
            if (gameManager.gameState == GameConfig.GameState.PLAYING) {
                // 根据玩家等级动态调整最大跳跃高度
                // 随着等级提升，增加跳跃能力，特别是3级及以上时显著提升跳跃高度
                val maxJumpHeight = when (player.bucketLevel) {
                    1 -> 50f   // 1级：基础跳跃高度
                    2 -> 60f   // 2级：小幅提升
                    3 -> 90f   // 3级：显著提升，确保能跨越最大平台间距
                    4 -> 100f  // 4级：继续提升
                    else -> 110f // 5级及以上：最大跳跃高度
                }
                
                // 直接使用根据等级计算的最大跳跃高度进行跳跃
                if (player.jump(maxJumpHeight)) {
                    VibrationUtils.vibrateForJump(this)
                }
            }
        }

        // 左移按钮点击事件
        leftButton.setOnClickListener {
            if (gameManager.gameState == GameConfig.GameState.PLAYING) {
                player.move(-GameConfig.PLAYER_MOVE_UNIT) // 向左移动一个单位
                VibrationUtils.vibrate(this) // 触发短震动反馈
            }
        }

        // 右移按钮点击事件
        rightButton.setOnClickListener {
            if (gameManager.gameState == GameConfig.GameState.PLAYING) {
                player.move(GameConfig.PLAYER_MOVE_UNIT) // 向右移动一个单位
                VibrationUtils.vibrate(this) // 触发短震动反馈
            }
        }

        // 设置结果弹窗按钮点击事件
        restartButton.setOnClickListener {
            restartGame()
        }

        backButton.setOnClickListener {
            backToSplash()
        }

        // 开始游戏
        startGameLoop()
    }

    /**
     * 开始游戏循环
     */
    private fun startGameLoop() {
        gameManager.startGame()
        lastFrameTime = System.nanoTime() // 初始化上一帧时间
        gameHandler.post(gameLoopRunnable)
    }

    /**
     * 停止游戏循环
     */
    private fun stopGameLoop() {
        gameHandler.removeCallbacks(gameLoopRunnable)
    }

    /**
     * 更新UI元素
     */
    private fun updateUI() {
        // 更新氦气罐等级显示
        bucketLevelText.text = String.format(getString(R.string.bucket_level_format), player.bucketLevel)
        
        // 更新氦气罐图标 - 为每个等级使用独立的资源引用
        val bucketIconResId = when (player.bucketLevel) {
            1 -> R.drawable.bucket_lv1
            2 -> R.drawable.bucket_lv2
            3 -> R.drawable.bucket_lv3
            4 -> R.drawable.bucket_lv4 // 为4级创建独立资源
            5 -> R.drawable.bucket_lv5 // 为5级创建独立资源
            6 -> R.drawable.bucket_lv6 // 为6级创建独立资源
            7 -> R.drawable.bucket_lv7 // 为7级创建独立资源
            8 -> R.drawable.bucket_lv8 
            9 -> R.drawable.bucket_lv9 
            10 -> R.drawable.bucket_lv10
            else -> R.drawable.bucket_lv10
        }
        bucketIcon.setImageResource(bucketIconResId)
        
        // 更新高度显示
        heightText.text = String.format(getString(R.string.height_format), gameManager.currentHeight)
        
        // 根据游戏状态启用/禁用按钮 - 移除!player.isJumping限制以支持连跳
        jumpButton.isEnabled = gameManager.gameState == GameConfig.GameState.PLAYING
        leftButton.isEnabled = gameManager.gameState == GameConfig.GameState.PLAYING
        rightButton.isEnabled = gameManager.gameState == GameConfig.GameState.PLAYING
    }

    /**
     * 显示游戏结果弹窗
     * @param isWin 是否胜利
     */
    private fun showResultDialog(isWin: Boolean) {
        stopGameLoop()
        
        // 设置弹窗内容
        if (isWin) {
            // 胜利情况
            gameOverText.text = getString(R.string.game_win_text)
        } else {
            // 失败情况，显示三行文本
            gameOverText.text = getString(R.string.game_over_text)
        }
        
        // 设置高度和等级信息
        finalHeightText.text = String.format(getString(R.string.final_height_text), gameManager.currentHeight)
        finalLevelText.text = String.format(getString(R.string.final_level_text), player.bucketLevel)
        
        // 触发震动反馈
        if (isWin) {
            VibrationUtils.vibrateForWin(this)
        } else {
            VibrationUtils.vibrateForLose(this)
        }
        
        // 显示弹窗
        resultDialog.visibility = View.VISIBLE
    }

    /**
     * 重新开始游戏
     */
    private fun restartGame() {
        // 隐藏结果弹窗
        resultDialog.visibility = View.GONE
        
        // 重置游戏状态
        gameManager.resetGame()
        
        // 重新开始游戏循环
        startGameLoop()
    }

    /**
     * 返回引导界面
     */
    private fun backToSplash() {
        val intent = Intent(this, SplashActivity::class.java)
        startActivity(intent)
        finish()
    }

    override fun onResume() {
        super.onResume()
        // 如果游戏状态是进行中，恢复游戏循环
        if (gameManager.gameState == GameConfig.GameState.PLAYING) {
            startGameLoop()
        }
    }

    override fun onPause() {
        super.onPause()
        // 暂停游戏循环
        stopGameLoop()
    }

    override fun onDestroy() {
        super.onDestroy()
        // 移除所有回调
        gameHandler.removeCallbacksAndMessages(null)
    }

    override fun onBackPressed() {
        // 返回引导界面
        backToSplash()
    }
}